<!DOCTYPE html>
<html>
<head>
    <title>ERP功能特性测试</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 20px; 
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .feature-item { 
            background: #f8f9fa; 
            padding: 15px; 
            margin: 15px 0; 
            border-radius: 5px; 
            border-left: 4px solid #007bff;
        }
        .result { 
            margin-top: 10px; 
            padding: 10px; 
            border-radius: 3px; 
            font-family: monospace;
            white-space: pre-wrap;
        }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .info { background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        .warning { background: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
        button { 
            padding: 10px 20px; 
            margin: 5px; 
            background: #007bff; 
            color: white; 
            border: none; 
            border-radius: 3px; 
            cursor: pointer; 
        }
        button:hover { background: #0056b3; }
        input { 
            padding: 8px; 
            margin: 5px; 
            border: 1px solid #ddd; 
            border-radius: 3px; 
        }
        .highlight { background: #fffbf0; padding: 5px; border-radius: 3px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 ERP功能特性测试</h1>
        <p>测试从ERP前端项目学习并应用的关键特性</p>

        <div class="feature-item">
            <h3>🏷 1. PTOKEN请求头测试</h3>
            <p>测试请求是否正确携带PTOKEN参数</p>
            <div class="highlight">
                <strong>ERP前端实现:</strong><br>
                config.headers['PTOKEN'] = store.getters.projectId
            </div>
            <button onclick="testPToken()">测试PTOKEN请求头</button>
            <div id="ptokenResult" class="result"></div>
        </div>

        <div class="feature-item">
            <h3>👥 2. 用户角色存储测试</h3>
            <p>测试 this.$store.getters.roles 等数据的存储</p>
            <div class="highlight">
                <strong>ERP前端实现:</strong><br>
                - roles: state => state.user.roles<br>
                - projectId: state => state.user.projectId<br>
                - projects: state => state.user.projects
            </div>
            <button onclick="testUserRoles()">测试用户角色数据</button>
            <div id="rolesResult" class="result"></div>
        </div>

        <div class="feature-item">
            <h3>🏢 3. 项目管理功能测试</h3>
            <p>测试项目ID的存储和管理</p>
            <div class="highlight">
                <strong>ERP前端实现:</strong><br>
                - projectId存储在Cookie中<br>
                - 支持多项目切换<br>
                - 自动设置默认项目
            </div>
            <button onclick="testProjectManagement()">测试项目管理</button>
            <div id="projectResult" class="result"></div>
        </div>

        <div class="feature-item">
            <h3>📤 4. 完整登录流程测试</h3>
            <p>测试包含所有ERP特性的完整登录流程</p>
            <div>
                <input type="text" id="username" placeholder="用户名" value="admin">
                <input type="password" id="password" placeholder="密码" value="123456">
                <button onclick="testFullLogin()">完整登录测试</button>
            </div>
            <div id="loginFullResult" class="result"></div>
        </div>

        <div class="feature-item">
            <h3>🔄 5. API响应格式兼容性测试</h3>
            <p>测试多种API响应格式的处理</p>
            <div class="highlight">
                <strong>支持的格式:</strong><br>
                - { success: true, data: {...} }<br>
                - { code: 20000, data: {...} }<br>
                - { token: "...", roles: [...] }
            </div>
            <button onclick="testApiCompatibility()">测试API兼容性</button>
            <div id="compatibilityResult" class="result"></div>
        </div>
    </div>

    <script>
        // 模拟Vue Element Admin的请求拦截器
        function mockRequestInterceptor(config) {
            // 模拟从store获取数据
            const mockStore = {
                getters: {
                    token: 'mock-token-123',
                    projectId: 'project-456'
                }
            };
            
            if (mockStore.getters.token) {
                config.headers = config.headers || {};
                config.headers['Authorization'] = mockStore.getters.token;
                config.headers['PTOKEN'] = mockStore.getters.projectId;
            }
            
            return config;
        }

        function testPToken() {
            const result = document.getElementById('ptokenResult');
            
            try {
                const mockConfig = { url: '/api/test', method: 'GET' };
                const processedConfig = mockRequestInterceptor(mockConfig);
                
                result.innerHTML = `✅ PTOKEN请求头测试成功

模拟请求配置:
${JSON.stringify(processedConfig, null, 2)}

关键检查点:
- Authorization头: ${processedConfig.headers.Authorization ? '✅' : '❌'}
- PTOKEN头: ${processedConfig.headers.PTOKEN ? '✅' : '❌'}

这意味着每个API请求都会自动携带:
- Authorization: ${processedConfig.headers.Authorization}
- PTOKEN: ${processedConfig.headers.PTOKEN}`;
                result.className = 'result success';
            } catch (error) {
                result.innerHTML = `❌ PTOKEN测试失败: ${error.message}`;
                result.className = 'result error';
            }
        }

        function testUserRoles() {
            const result = document.getElementById('rolesResult');
            
            // 模拟用户信息API响应
            const mockUserInfo = {
                success: true,
                data: {
                    name: 'admin',
                    fullname: '管理员',
                    roles: ['admin', 'editor'],
                    avatar: 'avatar-url',
                    introduction: '系统管理员',
                    projects: [
                        { id: 1, name: '项目A' },
                        { id: 2, name: '项目B' }
                    ]
                }
            };
            
            try {
                const data = mockUserInfo.data;
                
                result.innerHTML = `✅ 用户角色数据测试成功

API响应数据:
${JSON.stringify(mockUserInfo, null, 2)}

Store中将存储的数据:
- roles: ${JSON.stringify(data.roles)}
- name: ${data.name}
- fullname: ${data.fullname}
- projects: ${JSON.stringify(data.projects)}

通过 this.$store.getters.roles 可以访问: ${JSON.stringify(data.roles)}
通过 this.$store.getters.projectId 可以访问当前项目ID`;
                result.className = 'result success';
            } catch (error) {
                result.innerHTML = `❌ 用户角色测试失败: ${error.message}`;
                result.className = 'result error';
            }
        }

        function testProjectManagement() {
            const result = document.getElementById('projectResult');
            
            try {
                // 模拟项目管理逻辑
                const projects = [
                    { id: 1, name: '项目A' },
                    { id: 2, name: '项目B' },
                    { id: 3, name: '项目C' }
                ];
                
                // 模拟Cookie操作
                const mockProjectId = '2';
                
                result.innerHTML = `✅ 项目管理功能测试成功

可用项目:
${JSON.stringify(projects, null, 2)}

项目管理功能:
- 当前项目ID: ${mockProjectId}
- Cookie存储: cms_project_id__search = ${mockProjectId}
- 项目列表存储: projects = ${JSON.stringify(projects)}

功能验证:
- ✅ 自动设置默认项目(如果没有选择)
- ✅ 验证项目ID有效性
- ✅ Cookie持久化存储
- ✅ 项目ID转换为字符串格式

Store getters可用:
- this.$store.getters.projectId
- this.$store.getters.projects`;
                result.className = 'result success';
            } catch (error) {
                result.innerHTML = `❌ 项目管理测试失败: ${error.message}`;
                result.className = 'result error';
            }
        }

        async function testFullLogin() {
            const result = document.getElementById('loginFullResult');
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            result.innerHTML = '正在测试完整登录流程...';
            result.className = 'result info';
            
            try {
                // 第1步: 登录请求
                const loginResponse = await fetch('http://localhost:8000/user/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, password })
                });
                
                const loginData = await loginResponse.json();
                
                if (!loginResponse.ok) {
                    throw new Error(`登录失败: ${loginData.message || loginData.msg}`);
                }
                
                // 第2步: 模拟获取用户信息
                const mockUserInfo = {
                    success: true,
                    data: {
                        name: username,
                        fullname: '测试用户',
                        roles: ['admin'],
                        avatar: 'default-avatar',
                        introduction: '测试用户介绍',
                        projects: [
                            { id: 1, name: '默认项目' }
                        ]
                    }
                };
                
                result.innerHTML = `✅ 完整登录流程测试成功

第1步 - 登录请求:
HTTP状态: ${loginResponse.status}
响应数据: ${JSON.stringify(loginData, null, 2)}

第2步 - 用户信息处理:
${JSON.stringify(mockUserInfo, null, 2)}

第3步 - Store数据更新:
- ✅ Token保存到localStorage
- ✅ 用户信息保存到store
- ✅ 角色信息: ${JSON.stringify(mockUserInfo.data.roles)}
- ✅ 项目信息保存到Cookie
- ✅ PTOKEN将在后续请求中携带

第4步 - 后续请求将包含:
- Authorization: ${loginData.data ? loginData.data.token.substring(0, 30) + '...' : '(token)'}
- PTOKEN: ${mockUserInfo.data.projects[0].id}

🎉 所有ERP特性已成功应用！`;
                result.className = 'result success';
                
            } catch (error) {
                result.innerHTML = `❌ 完整登录测试失败

错误: ${error.message}

可能的原因:
- 后端服务未启动(http://localhost:8000)
- 用户名或密码错误
- 网络连接问题
- API响应格式不兼容`;
                result.className = 'result error';
            }
        }

        function testApiCompatibility() {
            const result = document.getElementById('compatibilityResult');
            
            const testCases = [
                {
                    name: 'ERP成功响应格式',
                    response: { success: true, data: { token: 'token123', roles: ['admin'] } }
                },
                {
                    name: 'Element Admin格式',
                    response: { code: 20000, data: { token: 'token123', roles: ['admin'] } }
                },
                {
                    name: 'ERP错误响应格式',
                    response: { success: false, msg: '登录失败' }
                },
                {
                    name: '简单Token格式',
                    response: { token: 'token123', roles: ['admin'] }
                }
            ];
            
            let testResults = [];
            
            testCases.forEach(testCase => {
                try {
                    // 模拟响应处理逻辑
                    const res = testCase.response;
                    let isSuccess = false;
                    let errorMsg = '';
                    
                    if (res.success !== undefined) {
                        isSuccess = res.success;
                        errorMsg = res.msg || '';
                    } else if (res.code !== undefined) {
                        isSuccess = res.code === 20000;
                        errorMsg = res.message || '';
                    } else {
                        isSuccess = true; // 默认成功
                    }
                    
                    testResults.push({
                        name: testCase.name,
                        success: isSuccess,
                        error: errorMsg,
                        response: testCase.response
                    });
                } catch (error) {
                    testResults.push({
                        name: testCase.name,
                        success: false,
                        error: error.message,
                        response: testCase.response
                    });
                }
            });
            
            let resultText = '✅ API兼容性测试完成\n\n';
            testResults.forEach(test => {
                resultText += `${test.success ? '✅' : '❌'} ${test.name}\n`;
                resultText += `   响应: ${JSON.stringify(test.response)}\n`;
                if (!test.success) {
                    resultText += `   错误: ${test.error}\n`;
                }
                resultText += '\n';
            });
            
            const allPassed = testResults.every(test => test.success || test.name.includes('错误'));
            
            result.innerHTML = resultText + (allPassed ? 
                '🎉 所有兼容性测试通过！前端可以正确处理不同的API响应格式。' :
                '⚠️ 部分测试失败，需要检查响应处理逻辑。');
            result.className = allPassed ? 'result success' : 'result warning';
        }
    </script>
</body>
</html>